<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8">
      <div class="bg-white rounded-lg shadow-sm p-6">
        <h1 class="text-2xl font-bold text-gray-900 mb-6">编辑个人资料</h1>
        
        <UForm :state="formState" class="space-y-6" @submit="handleSubmit">
          <!-- 头像上传 -->
          <div class="flex items-center space-x-6">
            <UAvatar
              size="2xl"
              :src="formState.avatar || userInfo?.avatar"
              :ui="{ background: 'bg-primary-100' }"
            />
            <div>
              <UButton
                color="gray"
                variant="soft"
                class="relative overflow-hidden"
              >
                <input
                  type="file"
                  class="absolute inset-0 opacity-0 cursor-pointer"
                  accept="image/*"
                  @change="handleAvatarChange"
                />
                <div class="flex items-center space-x-2">
                  <UIcon name="i-heroicons-arrow-up-tray" class="h-5 w-5" />
                  <span>更换头像</span>
                </div>
              </UButton>
              <p class="mt-2 text-sm text-gray-500">推荐使用正方形图片，JPG、PNG格式</p>
            </div>
          </div>

          <!-- 昵称 -->
          <UFormGroup label="昵称" name="nickname">
            <UInput v-model="formState.nickname" placeholder="请输入昵称" />
          </UFormGroup>

          <!-- 性别 -->
          <UFormGroup label="性别" name="gender">
            <div class="flex space-x-4">
              <div 
                class="gender-option flex-1 p-4 border rounded-lg cursor-pointer transition-all duration-200 flex items-center justify-center"
                :class="{
                  'border-primary-500 bg-primary-50 shadow-sm': formState.gender === 'M',
                  'border-gray-200 hover:border-primary-300 hover:bg-gray-50': formState.gender !== 'M'
                }"
                @click="formState.gender = 'M'"
              >
                <UIcon name="i-heroicons-user" class="h-6 w-6 mr-2" :class="formState.gender === 'M' ? 'text-primary-600' : 'text-gray-500'" />
                <span :class="formState.gender === 'M' ? 'font-medium text-primary-700' : 'text-gray-700'">男</span>
              </div>
              <div 
                class="gender-option flex-1 p-4 border rounded-lg cursor-pointer transition-all duration-200 flex items-center justify-center"
                :class="{
                  'border-primary-500 bg-primary-50 shadow-sm': formState.gender === 'F',
                  'border-gray-200 hover:border-primary-300 hover:bg-gray-50': formState.gender !== 'F'
                }"
                @click="formState.gender = 'F'"
              >
                <UIcon name="i-heroicons-user" class="h-6 w-6 mr-2" :class="formState.gender === 'F' ? 'text-primary-600' : 'text-gray-500'" />
                <span :class="formState.gender === 'F' ? 'font-medium text-primary-700' : 'text-gray-700'">女</span>
              </div>
            </div>
          </UFormGroup>

          <!-- 个人简介 -->
          <UFormGroup label="个人简介" name="description">
            <UTextarea
              v-model="formState.description"
              :rows="4"
              placeholder="介绍一下你自己吧"
            />
          </UFormGroup>

          <!-- 社交链接 -->
          <UFormGroup label="社交链接" name="socialLinks">
            <div class="space-y-3">
              <div class="flex items-center space-x-3">
                <UIcon name="i-heroicons-globe-alt" class="h-5 w-5 text-gray-400" />
                <UInput v-model="formState.website" placeholder="个人网站" />
              </div>
              <div class="flex items-center space-x-3">
                <UIcon name="i-heroicons-camera" class="h-5 w-5 text-gray-400" />
                <UInput v-model="formState.instagram" placeholder="Instagram" />
              </div>
            </div>
          </UFormGroup>

          <!-- 提交按钮 -->
          <div class="flex justify-end space-x-3">
            <UButton color="gray" variant="soft" to="/me">取消</UButton>
            <UButton type="submit" color="primary">保存修改</UButton>
          </div>
        </UForm>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { userApi, type UserInfo } from '~/utils/user'

// 表单状态
const formState = ref({
  avatar: '',
  nickname: '',
  gender: '',
  description: '',
  website: '',
  instagram: ''
})

// 用户信息
const userInfo = ref<UserInfo | null>(null)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await api.get('/api/v1/users/me')
    const data = response
    if (data.code === 0) {
      userInfo.value = data.data
      // 填充表单
      formState.value = {
        avatar: userInfo.value.avatar,
        nickname: userInfo.value.nickname,
        gender: userInfo.value.gender,
        description: userInfo.value.description,
        website: userInfo.value.website,
        instagram: userInfo.value.instagram
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
  }
}

// 处理头像更改
const handleAvatarChange = async (event: Event) => {
  const file = (event.target as HTMLInputElement).files?.[0]
  if (file) {
    try {
      // 创建预览URL
      const reader = new FileReader()
      reader.onload = (e) => {
        formState.value.avatar = e.target?.result as string
      }
      reader.readAsDataURL(file)

      // 上传头像
      const response = await userApi.updateAvatar(file)
      if (response.code === 0) {
        useToast().add({
          title: '成功',
          description: '头像上传成功',
          color: 'green'
        })
        // 刷新用户信息
        await fetchUserInfo()
        
        // 触发自定义事件，通知其他组件（特别是default.vue）用户信息已更新
        window.dispatchEvent(new Event('user-info-changed'))
      }
    } catch (error) {
      console.error('头像上传失败:', error)
      useToast().add({
        title: '错误',
        description: '头像上传失败，请重试',
        color: 'red'
      })
    }
  }
}

// 处理表单提交
const handleSubmit = async () => {
  try {
    // 构建请求体
    const updateData = {
      nickname: formState.value.nickname,
      gender: formState.value.gender,
      description: formState.value.description
    }
    
    // 发送API请求
    const response = await api.put('/api/v1/users/me', updateData)
    
    if (response.code === 0) {
      // 显示成功提示
      useToast().add({
        title: '保存成功',
        description: '个人资料已更新',
        icon: 'i-heroicons-check-circle',
        color: 'green'
      })
      
      // 触发自定义事件，通知其他组件用户信息已更新
      window.dispatchEvent(new Event('user-info-changed'))
      
      // 跳转到个人主页
      navigateTo('/user/me')
    }
  } catch (error) {
    console.error('保存失败:', error)
    useToast().add({
      title: '保存失败',
      description: error instanceof Error ? error.message : '请稍后重试',
      color: 'red'
    })
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>